<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="操作证编号">
          <el-input
            v-model="searchParam.certificateCode"
            placeholder="请输入操作证编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="部门">
          <SelectOriganizationDangerGrant
            @change="(ids:string) => getSelectIds(ids, '使用部门')"
            :isCheckStrictly="true"
            :isMultiple="false"
            :disabled="false"
            :data="dataObject('使用部门')"
            :selectData="searchParam.departmentId"
          />
        </el-form-item>
        <el-form-item label="班组">
          <el-select
            v-model="searchParam.teamId"
            placeholder="请选择班组"
            clearable
            @change="handleTeamChange"
          >
            <el-option
              v-for="item in crewList"
              :key="`${item.id}`"
              :label="`${item.teamName}`"
              :value="`${item.id}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成员">
          <el-select
            v-model="searchParam.personId"
            placeholder="请选择成员"
            :disabled="!searchParam.teamId"
            clearable
          >
            <el-option
              v-for="item in memberList"
              :key="`${item.id}`"
              :label="`${item.memberName}`"
              :value="`${item.id}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备">
          <el-select
            v-model="searchParam.assetCode"
            placeholder="请选择设备"
            clearable
            :disabled="!searchParam.usingDepartmentId"
          >
            <el-option
              v-for="item in deviceList"
              :key="`${item.assetCode}`"
              :label="`${item.assetName}`"
              :value="`${item.assetCode}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发证时间">
          <el-date-picker
            v-model="searchParam.createTimeSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getcreateTime"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="操作证编号"
          prop="certificateCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="发证时间"
          prop="issuanceTime"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="部门名称"
          prop="departmentName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="班组名称"
          prop="teamName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="成员姓名"
          prop="personName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="设备编码"
          prop="assetCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="设备名称"
          prop="assetName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="备注"
          prop="remarks"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建人"
          prop="createdUserId"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建人名"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="更新时间"
          prop="lastUpdateTime"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="更新人"
          prop="lastUpdatedUserId"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="更新人名"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="240">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <eamoperationcertificate-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { getCrewListApi, getCrewMemberListApi } from "@/utils/commonData";

defineOptions({
  name: "MESEAMOPERATIONCERTIFICATE",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/eam/eamoperationcertificate/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  certificateCode: "",
  departmentId: "",
  teamId: "",
  teamCode: "",
  teamName: "",
  personName: "",
  assetId: "",
  createTimeSearch: [],
  createTimeStart: "",
  createTimeEnd: "",
};

const deleteParam = {
  api: "/eam/eamoperationcertificate/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  // 获取班组
  getCrews();
  getDevicesByDepartment();
  handleTeamChange();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/eamoperationcertificate/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开操作证表表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改操作证表";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增操作证表";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开操作证表表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "操作证表详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getcreateTime(data: any) {
  if (data) {
    searchParam.value.createTimeStart = data[0];
    searchParam.value.createTimeEnd = data[1];
  } else {
    searchParam.value.createTimeStart = "";
    searchParam.value.createTimeEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/eam/eamoperationcertificate/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}

function getSelectIds(ids: [] | string, item: string) {
  if (ids) {
    if (item == "使用部门") {
      searchParam.value.usingDepartmentId = ids;
      searchParam.value.departmentId = ids;
      getDevicesByDepartment(ids);
    } else if (item == "管理部门") {
      searchParam.value.manageDepartmentId = ids;
      personList.value = [];
      changeDept(ids, item);
    } else if (item == "维修部门") {
      searchParam.value.repairDepartmentId = ids;
      personList1.value = [];
      changeDept(ids, item);
    }
  } else {
    if (item == "使用部门") {
      searchParam.value.usingDepartmentId = "";
      searchParam.value.assetCode = "";
    } else if (item == "管理部门") {
      searchParam.value.manageDepartmentId = "";
      searchParam.value.assetManagerId = "";
      personList.value = [];
    } else if (item == "维修部门") {
      searchParam.value.repairDepartmentId = "";
      searchParam.value.repairManagerId = "";
      personList1.value = [];
    }
  }
}
const dataObject = (item: string) => {
  return {
    name:
      item == "使用部门"
        ? "使用部门"
        : item == "管理部门"
        ? "管理部门"
        : "维修部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};


// 获取维护班组列表
const crewList = ref(<any>[]);
async function getCrews() {
  crewList.value = (await getCrewListApi({ teamType: "1" })) || [];
}

//人员
const memberList = ref(<any>[]);

const handleTeamChange = async (teamId: any) => {
  // 清空已选人员
  searchParam.value.personId = "";

  if (teamId) {
    memberList.value =
      (await getCrewMemberListApi({ id: searchParam.value.teamId })) || [];
  } else {
    memberList.value = [];
  }
};

const deviceList = ref([]); // 设备列表

async function getDevicesByDepartment(id: string) {
  try {
    // 这里调用您的API，根据部门ID获取设备列表
    const { data } = await request({
      url: `/eam/eamoperationcertificate/queryEquipmentByDepartmentId/${id}`,
      method: "get",
    });
    deviceList.value = data;
  } catch (error) {
    ElMessage.error("获取设备列表失败");
  }
}
</script>
